<template>
    <div class="login-container">
        <div class="login-box">
            <div class="login-header">
                <h2>宠物商店后台</h2>
            </div>
            
            <!-- 登录类型切换 -->
            <div class="login-type-switch">
                <span 
                    :class="{ active: loginType === 'password' }" 
                    @click="loginType = 'password'"
                >用户名密码登录</span>
                <span 
                    :class="{ active: loginType === 'email' }" 
                    @click="loginType = 'email'"
                >邮箱验证码登录</span>
            </div>
            
            <!-- 用户名密码登录表单 -->
            <form v-if="loginType === 'password'" @submit.prevent="handleLogin">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" v-model="username" required placeholder="请输入用户名">
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" v-model="password" required placeholder="请输入密码">
                </div>
                <div v-if="error" class="error-message">{{ error }}</div>
                <button type="submit" class="login-btn" :disabled="loading">
                    {{ loading ? '正在登录...' : '登录' }}
                </button>
            </form>
            
            <!-- 邮箱验证码登录表单 -->
            <form v-else @submit.prevent="handleEmailLogin">
                <div class="form-group">
                    <label for="email">邮箱</label>
                    <input type="email" id="email" v-model="email" required placeholder="请输入邮箱">
                </div>
                <div class="form-group verification-code">
                    <label for="code">验证码</label>
                    <div class="code-input-group">
                        <input type="text" id="code" v-model="verificationCode" required placeholder="请输入验证码">
                        <button type="button" class="code-btn" :disabled="isSending" @click="sendVerificationCode">
                            {{ isSending ? `${countdown}秒后重新获取` : '获取验证码' }}
                        </button>
                    </div>
                </div>
                <div v-if="error" class="error-message">{{ error }}</div>
                <button type="submit" class="login-btn" :disabled="emailLoading">
                    {{ emailLoading ? '正在登录...' : '登录' }}
                </button>
            </form>
            
            <div class="login-footer">
                <p>还没有账号？<router-link to="/register">立即注册</router-link></p>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { api, getCode, verifyCode } from '@/network/api';

const username = ref('');
const password = ref('');
const loading = ref(false);
const error = ref<string | null>(null);
const router = useRouter();

// 新增登录类型状态
const loginType = ref('password');

// 邮箱验证码登录相关状态
const email = ref('');
const verificationCode = ref('');
const emailLoading = ref(false);
const isSending = ref(false);
const countdown = ref(60);

// 用户名密码登录逻辑（保持不变）
const handleLogin = async () => {
    loading.value = true;
    error.value = null;
    try {
        const response: any = await api.loginAdmin({
            username: username.value,
            passwordHash: password.value,
        });
        
        // 假设登录成功后，后端会返回一个 token
        if (response.data.code === 100 && response.data.data) {
            localStorage.setItem('user_info', JSON.stringify(response.data.data));
            // 登录成功，跳转到后台仪表盘
            router.push('/admin/dashboard');
        } else {
             error.value = '用户名或密码错误';
        }
    } catch (err: any) {
        console.error("登录失败:", err);
        // 不管服务器返回什么错误，对用户都显示用户名或密码错误
        error.value = '用户名或密码错误';
    } finally {
        loading.value = false;
    }
};

// 发送验证码
const sendVerificationCode = async () => {
    if (!email.value || isSending.value) return;
    
    try {
        isSending.value = true;
        await getCode(email.value);
        startCountdown();
    } catch (err: any) {
        console.error('发送验证码失败:', err);
        error.value = err.response?.data?.message || '发送验证码失败，请稍后重试。';
        isSending.value = false;
    }
};

// 倒计时
const startCountdown = () => {
    countdown.value = 60;
    const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
            clearInterval(timer);
            isSending.value = false;
        }
    }, 1000);
};

// 邮箱验证码登录
const handleEmailLogin = async () => {
    // 验证邮箱和验证码是否输入
    if (!email.value) {
        error.value = '请输入邮箱';
        emailLoading.value = false;
        return;
    }

    if (!verificationCode.value) {
        error.value = '请输入验证码';
        emailLoading.value = false;
        return;
    }

    // 验证码格式验证
    if (verificationCode.value.length !== 6) {
        error.value = '验证码格式不正确，请输入6位数字';
        emailLoading.value = false;
        return;
    }

    emailLoading.value = true;
    error.value = null;
    
    try {
        console.log('开始验证验证码，邮箱:', email.value, '验证码:', verificationCode.value);
        
        // 验证验证码
        const verifyResult = await verifyCode(email.value, verificationCode.value);
        
        console.log('验证码校验响应:', verifyResult);
        
        // 严格检查验证码校验结果
        if (verifyResult && verifyResult.code === 100 && verifyResult.data) {
            console.log('验证码校验成功，用户数据:', verifyResult.data);
            
            // 保存用户信息
            const userInfo = {
                data: verifyResult.data,
                // 如果后端返回了token，使用后端返回的token，否则生成一个临时token
                token: verifyResult.data.token || 'email-login-token-' + Date.now()
            };
            
            console.log('保存用户信息:', userInfo);
            localStorage.setItem('user_info', JSON.stringify(userInfo));
            
            // 登录成功，跳转到后台仪表盘
            router.push('/admin/dashboard');
        } else {
            console.error('验证码校验失败:', verifyResult);
            error.value = verifyResult?.message || '验证码验证失败，请检查验证码是否正确';
        }
    } catch (err: any) {
        console.error("邮箱登录失败:", err);
        error.value = err.response?.data?.message || err || '登录失败，请检查验证码';
    } finally {
        emailLoading.value = false;
    }
};
</script>

<style scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f2f5;
    background-image: url('https://images.unsplash.com/photo-1548343163-cb7ef5658536?q=80&w=2070&auto=format&fit=crop');
    background-size: cover;
    background-position: center;
}

.login-box {
    width: 100%;
    max-width: 400px;
    padding: 40px;
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 12px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(5px);
}

.login-header {
    text-align: center;
    margin-bottom: 30px;
}

.login-header h2 {
    font-size: 2em;
    color: #333;
    font-weight: 600;
    margin: 0;
}

/* 登录类型切换 */
.login-type-switch {
    display: flex;
    justify-content: space-around;
    margin-bottom: 20px;
    border-bottom: 1px solid #eee;
}

.login-type-switch span {
    padding: 10px 15px;
    cursor: pointer;
    position: relative;
    color: #666;
    transition: all 0.3s;
}

.login-type-switch span.active {
    color: #3498db;
    font-weight: 500;
}

.login-type-switch span.active::after {
    content: '';
    position: absolute;
    bottom: -1px;
    left: 0;
    width: 100%;
    height: 2px;
    background-color: #3498db;
}

.form-group {
    margin-bottom: 20px;
    text-align: left;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #555;
}

.form-group input {
    width: 100%;
    padding: 12px 15px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 1em;
    box-sizing: border-box;
    transition: border-color 0.3s, box-shadow 0.3s;
}

.form-group input:focus {
    outline: none;
    border-color: #3498db;
    box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
}

/* 验证码输入组 */
.verification-code .code-input-group {
    display: flex;
    gap: 10px;
}

.verification-code input {
    flex: 1;
}

.verification-code .code-btn {
    padding: 0 15px;
    background-color: #3498db;
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 0.9em;
    white-space: nowrap;
    cursor: pointer;
    transition: background-color 0.3s;
}

.verification-code .code-btn:hover {
    background-color: #2980b9;
}

.verification-code .code-btn:disabled {
    background-color: #bdc3c7;
    cursor: not-allowed;
}

.login-btn {
    width: 100%;
    padding: 12px;
    background-color: #3498db;
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 1.1em;
    font-weight: 500;
    cursor: pointer;
    transition: background-color 0.3s, transform 0.2s;
}

.login-btn:hover {
    background-color: #2980b9;
    transform: translateY(-2px);
}

.login-btn:disabled {
    background-color: #bdc3c7;
    cursor: not-allowed;
    transform: none;
}

.error-message {
    color: #e74c3c;
    background-color: #fdd;
    border: 1px solid #e74c3c;
    border-radius: 6px;
    padding: 10px;
    margin-bottom: 20px;
    text-align: center;
    font-size: 0.9em;
}

.login-footer {
    margin-top: 20px;
    text-align: center;
    font-size: 0.9em;
}

.login-footer a {
    color: #3498db;
    text-decoration: none;
    font-weight: 500;
}

.login-footer a:hover {
    text-decoration: underline;
}
</style> 